﻿using System;
using System.Collections.Generic;
using SdmxMl.Common;
using SdmxMl.Manager;
using SdmxMl.Structure;
using SdmxMl.GenericMetadata;
using System.Text;
using Ch.Admin.Bfs.Sms.Sdmx.Extension.CodeBook.Configuration;

namespace Ch.Admin.Bfs.Sms.Sdmx.Extension.CodeBook.Meta
{
    public class CatVarProvider : BaseMetaProvider, IMetaProvider
    {
        
        private ConceptSchemeType cst;

        public CatVarProvider(string lang, string conceptSchemeFullId, BookConfiguration cfg)
            : base(lang, conceptSchemeFullId, cfg)
        {
            try
            {
                // Get required maintenable artefact
                ArtefactRefTyped art = new ArtefactRefTyped(SdmxArtefactType.Concepts, fullIdKey);
                sm.LoadMissingArtefactsFromRegistry(art);
                cst = sm.GetArtefact(art) as ConceptSchemeType;

                ProduceHierarchy(cst);
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Unable to obtain related metadata for " + fullIdKey, ex);
            }
        }

        private string GetReferedQuestFullId(ConceptSchemeType cst)
        {
            string fid = null;
            Annotation ann = cst.AnnotationList.GetAnnotationType("QUEST_LINK");
            if (ann != null && ann.Url != null)
            {
                UrnParser p = new UrnParser(ann.Url.ToString());
                if (p.IsSupported && p.ArType == SdmxArtefactType.MetadataSet)
                     fid = p.FullIdent;
            }
            return fid;
        }

        private void ProduceHierarchy(ConceptSchemeType cst)
        {
            hierarchy = new Hierarchy();
            hierarchy.Add(new HierarchyNode(cst.Id, cst.Name.GetForLanguage(lg), cst.Description.GetForLanguage(lg), cst));
            List<ISdmxHierarchyListItem> listItems = new List<ISdmxHierarchyListItem>(cst.ConceptList);
            FillRecurse(hierarchy[0].Nodes, listItems, "");
            hierarchy[0].refArt = GetReferedQuestFullId(cst);
        }

        private void FillRecurse(Hierarchy nodes, List<ISdmxHierarchyListItem> listItems, string parentId)
        {
            List<ISdmxHierarchyListItem> listChild = GetChildList(parentId, listItems);
            foreach (ISdmxHierarchyListItem item in listChild)
            {
                HierarchyNode childNode = new HierarchyNode(item.Id, item.Name.GetForLanguage(lg), ((ConceptType) item).Description.GetForLanguage(lg), item);
                nodes.Add(childNode);
                listItems.Remove(item);
                FillRecurse(childNode.Nodes, listItems, item.Id);
            }
        }
    }
}
